package com.taobao.tql;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.UserGetResponse;
import com.taobao.tql.common.TqlConstants;
import com.taobao.tql.hsf.HsfDataTranster;
import com.taobao.tql.parser.JsEngine;
import com.taobao.tql.parser.JsonParse;
import com.taobao.tql.parser.TqlSelectParser;
import com.taobao.tql.scan.GetApiImpl;

/**
 * 
 * 
 * @类名称：TQLQuery
 * @类描述：查询主类
 * @创建人：卫缺
 * @修改人：卫缺
 * @修改时间：2011-6-28 下午04:57:07
 * @修改备注：
 * @version 1.0.0
 * 
 */
public class TQLQuery {

	private static Logger logger = Logger.getLogger(TQLQuery.class.getName());
	private String TQLStr = null;

	private String strAppKey = null;

	public TQLQuery(String TQLStr, String strAppKey) {
		this.TQLStr = TQLStr;
		this.strAppKey = strAppKey;
	}

	public TQLQuery() {
	}

	/**
	 * TQLQueryAll 解析数据
	 * 
	 * @param TQLStr
	 * @return Object
	 * @since 1.0.0
	 */
	public String TQLQueryExcu() {
		// 解析SQL
		TqlSelectParser tqlParser = new TqlSelectParser(TQLStr);
		if (tqlParser.getTqlParserBean().getException() != null) {
			return "TQL表达式不正确!!" + tqlParser.getTqlParserBean().getException();
		}
		// 表名称
		String tableStr = tqlParser.getTqlParserBean().getTabName();
		String conditions = tqlParser.getTqlParserBean().getWhere();
		// fields
		String fields = tqlParser.getTqlParserBean().getFromItem();
		if (tableStr == null) {
			return "请输入对象名称table!!";
		}
		// 查询搜有的API
		if ("tables".equals(tableStr)) {
			return GetApiImpl.getInstantce().showAllApis();
		}
		// 判断是否支持api
		if (!"seller".equals(tableStr) && GetApiImpl.getInstantce().getApiKey(tableStr) == null) {
			return "不支持对象名称[" + tableStr + "]的查询!";
		}
		tableStr = tableStr.toLowerCase();
		if (conditions == null) {
			return "请输入where查询条件!!";
		}
		// 放入条件
		TreeMap<String, String> whereMap = new TreeMap<String, String>();
		conditions = conditions.toLowerCase();
		String[] condAnds = conditions.split("and");
		for (String strCond : condAnds) {
			String[] conds = strCond.split("=");
			String condsKey = conds[0].trim().toLowerCase();
			whereMap.put(condsKey, conds[1].trim());
		}

		// 测试直接调用HSF服务
		if ("seller".equals(tableStr)) {

			return HsfDataTranster.getTaobaoApiGet(whereMap, tableStr, fields);
		} else {
			String strKey = "";
			// 目前只支持get
			String strAppRequest = "getrequest";
			// 判断用户是否输入com.taobao.user样式的接口
			if (tableStr.indexOf(".") <= 0) {
				strKey = "taobao." + tableStr + ".get";
			} else {
				strKey = tableStr;
				strAppRequest = null;
			}
			if (fields == null || "[*]".equals(fields)) {
				fields = JsEngine.getFileds(strKey);
				logger.info(fields);
			}

			// 判断必输字段
			String mustInput = JsonParse.isMustInput(whereMap, GetApiImpl.getInstantce().getApiKey(tableStr), strKey);
			if (mustInput != null) {
				return mustInput;
			}
			logger.info(mustInput);

			if (strAppRequest == null) {
				tableStr = tableStr.substring(0, tableStr.lastIndexOf("."));
				tableStr = tableStr.substring(tableStr.indexOf(".") + 1, tableStr.length());
				tableStr = tableStr.replaceAll("\\.", "");
				strAppRequest = "getrequest";
			}
			return getTaobaoApiGet(whereMap, tableStr, fields, strAppRequest);

		}

	}

	/**
	 * 
	 * getTaobaoApiGet 从TOPAPI获取相关数据
	 * 
	 * @param client
	 * @return String
	 * @since 1.0.0
	 */
	private String getTaobaoApiGet(Map<String, String> treeMap, String tabName, String fields, String strAppRequest) {

		// 动态查找get API
		// TaobaoRequest request = null;
		Class<?> getReq = null;
		Object getReqObj = null;
		String apiName = getApiStr(tabName, strAppRequest);
		// 所有的方法
		Method[] allMethod = null;
		// 参数列表
		Object[] args1 = null;
		try {

			getReq = Class.forName(apiName);
			getReqObj = getReq.newInstance();
			// 获取所有的方法
			allMethod = getReqObj.getClass().getMethods();
			// Class<?> partypes[] = new Class[]{String.class};
			Map<String, String> condMap = new TreeMap<String, String>();
			for (Map.Entry<String, String> temp : treeMap.entrySet()) {
				String tempPoprName = temp.getKey();
				String[] condAnds = tempPoprName.split("_");
				StringBuilder strBuild = new StringBuilder("set");
				// 转化为set方法
				for (String strCond : condAnds) {
					// 查找首字母
					String firstName = strCond.substring(0, 1);
					strBuild.append(firstName.toUpperCase());
					strBuild.append(strCond.substring(1, strCond.length()));
				}
				condMap.put(strBuild.toString(), temp.getValue());
			}
			for (Method tempMethod : allMethod) {
				String methodName = tempMethod.getName();
				
				if (methodName.startsWith("set")) {

					if (methodName.equals("setFields")) {
						args1 = new String[] { fields };// 参数列表
						tempMethod.invoke(getReqObj, args1);
		/*			} else if (methodName.equals("setNick")) {
						if (treeMap.get("nick") != null) {
							args1 = new Object[] { String.valueOf(condMap.get("nick")) };// 参数列表
							tempMethod.invoke(getReqObj, args1);
						} else {
							return "请输入nick查询条件!";
						}*/
					} else if (condMap.get(methodName) != null) {
						Class[] cc = tempMethod.getParameterTypes();
						if (cc.length == 1) {
							String type = cc[0].getName(); // parameter type
							if (type.equals("java.lang.String")) {
								tempMethod.invoke(getReqObj, new Object[] { condMap.get(methodName) });
							} else if (type.equals("int") || type.equals("java.lang.Integer")) {
								tempMethod.invoke(getReqObj, new Object[] { new Integer(condMap.get(methodName)) });
							} else if (type.equals("long") || type.equals("java.lang.Long")) {
								tempMethod.invoke(getReqObj, new Object[] { new Long(condMap.get(methodName)) });
							} else if (type.equals("boolean") || type.equals("java.lang.Boolean")) {
								tempMethod.invoke(getReqObj, new Object[] { Boolean.valueOf(condMap.get(methodName)) });
							} else if (type.equals("java.util.Date")) {
								Date date = null;// DateUtil.parseDateTime(param);
								if (date != null)
									tempMethod.invoke(getReqObj, new Object[] { date });
							}
						}

					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return e.fillInStackTrace().toString();
		}

		// 构造TaobaoClient
		Class<?> taobaoClient = null;
		Object taobaoObj = null;
		// 返回
		Object responseObj = null;
		try {
			taobaoClient = Class.forName("com.taobao.api.DefaultTaobaoClient");
			Class<?> partypes[] = new Class[] { String.class, String.class, String.class, String.class };
			Constructor<?> dftClient = taobaoClient.getConstructor(partypes);
			Object arglist[] = new Object[4];
			arglist[0] = TqlConstants.TOP_URL2;
			// APP KEY
			if (strAppKey != null) {
				arglist[1] = strAppKey;
			} else {
				arglist[1] = TqlConstants.APP_KEY;
			}
			arglist[2] = TqlConstants.APP_SECRET;
			arglist[3] = Constants.FORMAT_XML;

			// 获取对象实例
			taobaoObj = dftClient.newInstance(arglist);

			// 执行excude方法
			Class<?> executes[] = new Class[] { TaobaoRequest.class };
			// 作用域字段
			Method setFields = taobaoObj.getClass().getMethod("execute", executes);
			args1 = new Object[] { getReqObj };// 参数列表
			responseObj = setFields.invoke(taobaoObj, args1);

		} catch (Exception e) {
			logger.error(e.getMessage());
			return e.fillInStackTrace().toString();
		}
		// 返回结果输出
		if (responseObj instanceof TaobaoResponse) {
			TaobaoResponse response = (TaobaoResponse) responseObj;
			if (response != null && response.isSuccess()) {
				logger.info("getBody():::" + response.getBody());
				return response.getBody();
			} else if (response != null && !response.isSuccess()) {
				return response.getBody();
			}
		}
		return "error";
	}

	/**
	 * 
	 * getXmlFromStr(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
	 * 
	 * @param inputStr
	 * @return String
	 * @since 1.0.0
	 */
	public String getXmlFromStr(String inputStr) {
		StringBuilder strBuild = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
		strBuild.append("<resultmsg>");
		strBuild.append(inputStr);
		strBuild.append("</resultmsg>");
		return strBuild.toString();
	}

	/**
	 * 从静态方法中获取常量类
	 * 
	 * @param tabName
	 * @param appendStr
	 * @return
	 */
	public String getApiStr(String tabName, String appendStr) {
		StringBuilder strBuild = new StringBuilder(tabName);
		if (appendStr != null) {
			strBuild.append(appendStr);
		}
		if (GetApiImpl.getInstantce().geTaobaoApi().get(strBuild.toString()) != null) {
			return GetApiImpl.getInstantce().geTaobaoApi().get(strBuild.toString());
		}
		return null;
	}

	/**
	 * 
	 * main(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
	 * 
	 * @param arges
	 *            void
	 * @since 1.0.0
	 */
	public static void main(String[] arges) {
		/*
		 * ScanGet scanGet = new ScanGet(); Set<Class<?>> apiClasses =
		 * scanGet.getClasses("com.taobao.api.request."); for(Class tempCls :
		 * apiClasses) { System.out.println(tempCls.getName()); }
		 */

		// GetApiImpl.getInstantce().geTaobaoApi();

		TaobaoClient client = new DefaultTaobaoClient(TqlConstants.TOP_URL2, TqlConstants.APP_KEY, TqlConstants.APP_SECRET);
		UserGetRequest req = new UserGetRequest();
		req.setFields("nick,sex,buyer_credit,seller_credit ,created,last_visit");
		req.setNick("hz0799");
		UserGetResponse response = null;
		try {
			response = client.execute(req);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (response.isSuccess()) {
			System.out.println(response.getUser().getNick());
		} else {
			// deal error
		}

	}

}
